/**
 * Created by bian on 16-12-14.
 */
import "../base.js"
import {AjaxError,errorHandler,AJAXERROR} from "../Error"

// action type
export const REFRESH = "REFRESH"
export const SORT = "SORT"
export const SEARCH = "SEARCH"
exports.AJAXERROR = AJAXERROR
export const FILTER = "FILTER"
export const CHANGEPAGE = "CHANGEPAGE"
export const SELECTCOURSE = "SELECTCOURSE"
export const MOVE = "MOVE"
export const ADDCOURSE = "ADDCOURSE"
export const DELETEITEM = "DELETEITEM"

// action functions
export function getCourseList() {
    return fetch("/education/carousels/all")
        .then(response => response.json())
        .then(json => {
            console.log(json.msg)
            if(json.status !== 200){
                throw new AjaxError(json,-1);
            }
            return {
                type : REFRESH,
                courses : json.msg
            }
        }).catch(errorHandler)
}

export function sortCourseList(sortIdx,sortFlag){
    return {
        type : SORT,
        sortIdx : sortIdx,
        sortFlag : sortFlag
    }
}

export function searchCourse(searchText){
    return {
        type : SEARCH,
        searchText : searchText
    }
}

/**
 * 根据类别筛选课程
 * @param filterName
 * @returns {{type: string, filterName: *}}
 */
export function filterCourse(filterName) {
    return {
        type : FILTER,
        filterName : filterName
    }
}

/**
 * 改变页数或者每页个数
 * @param page
 * @param limit
 */
export function changePage(page,limit) {
    return {
        type : CHANGEPAGE,
        page : page,
        limit : limit
    }
}

/**
 * 选中课程
 * @param course
 */
export function selectCourse(course){
    return {
        type : SELECTCOURSE,
        course : course,
    }
}

/**
 * 上移或者下移
 * @param direction
 * @param course
 * @returns {{type: string}}
 */
export function move(direction,course){
    return {
        type : MOVE,
        direction : direction,
        course : course
    }
}

/**
 * 上传课程
 */
export function addCourse(item){
    return fetch(`/education/admin/carousels/add`, {
        method: "POST",
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            img : item.img,
            href : item.href
        })
    })
        .then(res => res.json())
        .then(json => {
            return {
                type : ADDCOURSE,
                course : json.msg
            }
        }).catch(errorHandler)
}

/**
 * 删除条目
 */
export function delItem(item){
    return fetch(`/education/admin/carousels/del`,{
        method : "POST",
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            id : item.id
        })
    })
        .then(res => res.json())
        .then(json => {
            return {
                type : DELETEITEM,
                item : item
            }
        }).catch(errorHandler)
}